// echo aux function only, should not compile alone.
// -r:"../../Backend/System.IO.FileSystem.dll"

//! 编译方法，目前来说只能是自己改上面那行字，把缺的东西都补齐，之后送命令提示符或者用python脚本编译。
//! windows就是一坨shit……连通配符都不支持……不然我至少能写出类似 dotnet C:\Program Files\dotnet\sdk\*\Roslyn\bincore\csc.dll 这样的语法

// -r:"../../The Scroll of Taiwu_Data/Managed/Mono.Cecil.dll" -r:"../../The Scroll of Taiwu_Data/Managed/System.Core.dll"   -r:"../../The Scroll of Taiwu_Data/Managed/System.Composition.AttributedModel.dll" -r:"../../Backend/System.Runtime.dll"
/**
 *  Everyone's Unity Game Plugin
 *  Copyright (C) 2022 Neutron3529
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
//! 这是一个自带文档注释的Mod，虽然代码很shit，但里面有不少注释，或许会对之后准备玩过月逻辑的人有帮助。
//! 所有文档注释会用//!开头，请注意搜索
//! 首先是前后端，前端对后端的调用会先被塞进 ProcessMethodCall，之后分发给对应domain的CallMethod，由CallMethod进行进一步的分发。借助这一点，我们可以快速找到前端调用究竟是在使用哪个函数。
using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
using static Utils.Logger;
using static Utils.CharacterMod;

using Config.EventConfig;
using GameData.Domains.TaiwuEvent;
using GameData.Domains.TaiwuEvent.Enum;

namespace Neutron3529.ChaosEvents {
    public partial class ChaosEvents : EventPackage {
        public 高僧.高僧 E04(){
            var o=new 高僧.高僧();
            {
                var taiwuEvent = GameData.Domains.DomainManager.TaiwuEvent.GetEvent("fb38f657-6ed0-41e4-a0c2-c82afb49762f"); // @人物互动-恩义互动
                var lst=taiwuEvent.EventConfig.EventOptions.ToList();
                lst.Insert(lst.Count-1, o.EventOptions[0]);
                taiwuEvent.EventConfig.EventOptions=lst.ToArray();
            }
            {
                var taiwuEvent = GameData.Domains.DomainManager.TaiwuEvent.GetEvent("c52b570b-85c3-4bd7-82a0-b4b1a42be456"); // 高僧-超度法会-入口
                var lst=taiwuEvent.EventConfig.EventOptions.ToList();
                for(int i=0;i<lst.Count;i++){
                    if(lst[i].OptionKey == "Option_1664093685"){
                        var opt=lst[i];
                        lst[i].GetReplacedContent=()=>{
                            try{
                                var waitingReincarnationChars = new HashSet<int>();
                                var saved=0;
                                var waiting=0;
                                GameData.Domains.DomainManager.Character.GetAllWaitingReincarnationCharIds(waitingReincarnationChars);
                                foreach (int charId in waitingReincarnationChars) {
                                    if (!GameData.Domains.DomainManager.Building.IsCharOnSamsaraPlatform(charId)) {
                                        if(GameData.Domains.DomainManager.Extra.IsSavedSoul(charId)){saved++;}else{waiting++;}
                                    }
                                }
                                return waiting!=0?$"（举办法会罢，毕竟{saved+waiting}个灵魂之间，仍有{waiting}人等待超度……）":$"（举办法会罢，虽{saved}个灵魂之间再无人等待超度，但熟悉熟悉往生咒语也是好的……）";
                            } catch(Exception e){
                                logex(e);
                            }
                            return string.Empty;
                        };
                        break;
                    }
                }
                lst.Insert(lst.Count-1,o.EventOptions[2]);
                taiwuEvent.EventConfig.EventOptions=lst.ToArray();
            }
            {
                var taiwuEvent = GameData.Domains.DomainManager.TaiwuEvent.GetEvent("245a7e65-0e12-4fd6-aace-ca57cb5b3b10"); // 遇到入魔人_伤重-使用剑柄-成功
                var lst=taiwuEvent.EventConfig.EventOptions.ToList();
                lst.Insert(0, o.EventOptions[1]);
                taiwuEvent.EventConfig.EventOptions=lst.ToArray();
            }
            return o;
        }
    }
    namespace 高僧 {
        public class 高僧 : EventContainer {
            public 高僧() :base("Prof.高僧", "70b4d45d-ba15-423d-b94e-b40e348eb9c4"){
                this.EventOptions = new TaiwuEventOption[3];
                for(int i=0;i<this.EventOptions.Length;i++){
                    var op=new TaiwuEventOption {
                        OptionKey = "Option_352904"+(i+1).ToString("02"),
                        OnOptionSelect = new Func<string>(this.OnOptionSelect(i)),
                        OnOptionVisibleCheck = new Func<bool>(this.OnCheckOptionCondition(i)),
                        OnOptionAvailableCheck = new Func<bool>(this.OnCheckEventCondition),
                        GetReplacedContent = new Func<string>(this.Desc(i)),
                        GetExtraFormatLanguageKeys = new Func<List<string>>(this.GetExtraFormatLanguageKeys)
                    };
                    this.EventOptions[i]=op;
                }
            }
            private Func<bool> OnCheckOptionCondition(int index){
                switch(index){
                    case 0:
                    case 1:return ()=> {
                        var pd=GameData.Domains.TaiwuEvent.EventHelper.EventHelper.GetCurrentProfessionData();
                        if(pd!=null && pd.TemplateId == 6 && pd.IsSkillUnlocked(1)){
                            var character = this.EventOptions[index].ArgBox.GetCharacter("CharacterId");
                            return character!=null;
                        }
                        return false;
                    };
                    case 2: return ()=>{
                        var pd=GameData.Domains.TaiwuEvent.EventHelper.EventHelper.GetCurrentProfessionData();
                        if(pd!=null && pd.TemplateId == 6){
                            var waitingReincarnationChars = new HashSet<int>();
                            GameData.Domains.DomainManager.Character.GetAllWaitingReincarnationCharIds(waitingReincarnationChars);
                            return !waitingReincarnationChars.All(charId=>GameData.Domains.DomainManager.Extra.IsSavedSoul(charId));
                        }
                        return false;
                    };
                    default: return ()=>false;
                }
            }
            MethodInfo RemoveElement_WaitingReincarnationChars=typeof(GameData.Domains.Character.CharacterDomain).GetMethod("RemoveElement_WaitingReincarnationChars",(BindingFlags)(-1));
            FieldInfo _taiwuCurrProfessionId=typeof(GameData.Domains.Extra.ExtraDomain).GetField("_taiwuCurrProfessionId",(BindingFlags)(-1));
            private unsafe Func<string> OnOptionSelect(int index){
                switch(index){
                    case 0:return ()=> {
                        var ArgBox=this.EventOptions[index].ArgBox;
                        var targetChar = ArgBox.GetCharacter("CharacterId");
                        var cname=Name(targetChar);

                        targetChar.RecordFameAction(this.context, 16, -1, 20, false);
                        targetChar.RecordFameAction(this.context, 38, -1, 20, false);
                        targetChar.RecordFameAction(this.context, 52, -1, 20, false);
                        targetChar.RecordFameAction(this.context, 54, -1, 20, false);
                        return Goto($"冬至过了那整三天，{cname}降生在驻马店\n三仙送来一箱苹果，还有五斤肉十斤面\n\n（通过宣经讲书，世人对{cname}的名誉认知有了变化）","（不错不错……）", index);
                    };
                    case 1: return ()=>{
                        var character = this.EventOptions[index].ArgBox.GetCharacter("CharacterId");
                        var RoleTaiwu = this.EventOptions[index].ArgBox.GetCharacter("RoleTaiwu");
                        var cname=Name(character);
                        var tname=Name(RoleTaiwu);
                        var id=character.GetId();
                        GameData.Domains.TaiwuEvent.EventHelper.EventHelper.KillCharacter(character.GetId(), character.GetId(), GameData.Domains.TaiwuEvent.Enum.EKillCharacterType.KillInPublic);
                        var x=character.preexistenceCharIds();
                        GameData.Domains.DomainManager.Character.RecordDeletedFromOthersPreexistence(context, ref x);
                        var preexistenceCharIds=RoleTaiwu.preexistenceCharIds();
                        if (preexistenceCharIds.Count < 9)
                        {
                            preexistenceCharIds.Add(context.Random, id);
                            RoleTaiwu.preexistenceCharIds(preexistenceCharIds, context);
                            RemoveElement_WaitingReincarnationChars.Invoke(GameData.Domains.DomainManager.Character,new object[]{new GameData.Utilities.IntPair(GameData.Domains.DomainManager.World.GetCurrDate(), id), this.context});
                            return Goto($"「此人于我有缘！」\n{tname}一声喊，吓得{cname}直从入魔状态之中清醒过来\n\n「你……」{cname}刚想说什么，见{tname}深吸一口气，像是想说些什么，连忙改口\n「也罢，众生皆苦，众生皆苦，多谢，多谢……」\n\n说罢，{cname}便自尽了\n\n<color=#lightgrey>（{tname}通过佛法，溶解了{cname}的灵魂）</color>","（不错不错……）", index);
                        } else {
                            GameData.Domains.DomainManager.Character.RecordDeletedFromOthersPreexistence(context, ref preexistenceCharIds);
                            preexistenceCharIds.Reset();

                            RoleTaiwu.preexistenceCharIds(preexistenceCharIds, context);
                            character.InvalidateSelfAndInfluencedCache(BaseMainAttributes_Id,context);
                            character.InvalidateSelfAndInfluencedCache(BaseLifeSkillQualifications_Id,context);
                            character.InvalidateSelfAndInfluencedCache(BaseCombatSkillQualifications_Id,context);
                            return Goto($"「此人于我有缘！」\n{tname}一声喊，吓得{cname}直从入魔状态之中清醒过来\n\n「你……」{cname}刚想说什么，见{tname}深吸一口气，像是想说些什么，连忙改口\n「也罢，众生皆苦，众生皆苦，多谢，多谢……」\n\n说罢，{cname}便自尽了\n\n<color=#lightgrey>（{tname}通过佛法，借助{cname}的灵魂为薪柴，将身上的九世灵魂一并烧了个干净）</color>","（不错不错……）", index, "23bef2eb-36b8-4a1b-b952-4c2b1db4d198");
                        }
                    };
                    case 2:return ()=> {
                        var RoleTaiwu = this.EventOptions[index].ArgBox.GetCharacter("RoleTaiwu");
                        var tname=Name(RoleTaiwu);
                        var closure=(GameData.Common.DataContext context)=>{
                            var cur=(int)_taiwuCurrProfessionId.GetValue(GameData.Domains.DomainManager.Extra);
                            _taiwuCurrProfessionId.SetValue(GameData.Domains.DomainManager.Extra,6); // bypass AddSavedSoul Check;
                            var cnt=0;
                            var waitingReincarnationChars = new HashSet<int>();
                            GameData.Domains.DomainManager.Character.GetAllWaitingReincarnationCharIds(waitingReincarnationChars);
                            foreach (int charId in waitingReincarnationChars) {
                                if(!GameData.Domains.DomainManager.Extra.IsSavedSoul(charId)){
                                    GameData.Domains.DomainManager.Extra.AddSavedSoul(context, charId);
                                    cnt++;
                                }
                            }
                            _taiwuCurrProfessionId.SetValue(GameData.Domains.DomainManager.Extra, cur); // bypass AddSavedSoul Check;
                            return cnt;
                        };
                        var cnt=closure(this.context);
                        GameData.DomainEvents.Events.RegisterHandler_AdvanceMonthFinish((context)=>closure(context));
                        return Goto($"昔日有个目连僧，救母亲临地狱门\n借问灵山多少路，十万八千有余零\n\n<color=#lightgrey>目连僧的母亲深知佛门诈骗功底与PUA技术，而目连僧一心向佛\n佛祖一怒之下将目连僧的母亲关进地狱，而目连僧也只好用那些「为我佛工作」赚得的功德去将母亲从地狱中赎出\n\n（{tname}轻轻唱着佛家这段著名公案，吓得{cnt}个魂灵一个接一个都去投胎了）\n<s>（这段公案的警示作用是如此之强大，以至于在下次SL之前，大概不会有灵魂来打扰高僧了）</s></color>","（阿弥陀佛……）", index);
                    };
                    default: return ()=>string.Empty;
                }
            }
            public override Func<string> Desc(int i){
                switch(i){
                    case 0:
                        return ()=>"（为其背书……）";
                    case 1:
                        return ()=>"吾当以己身度魔！（用佛法将"+Name(this.EventOptions[i].ArgBox.GetCharacter("CharacterId"))+"的灵魂吸纳为自己的轮回……）";
                    case 2:
                        return ()=>"（自己投胎，别来烦我……）";
                    default: return ()=>string.Empty;
                }
            }
        }
    }
}
